#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/wait.h>

using namespace std;

void Writer(int write_fd) {
    string input_s = "Im a father";
    pid_t self = getpid();

    char buffer[1023];
    buffer[0] = 0;  //清空
    snprintf(buffer, sizeof(buffer), "%s-%d-%d", input_s.c_str(), self);
    write(write_fd, buffer, strlen(buffer));
}

void Reader(int read_fd) {
    char buffer[1024];

    buffer[0] = 0;
    ssize_t n = read(read_fd, buffer, sizeof(buffer));
    buffer[n] = '\0';
    cout << "child output:" <<  buffer << endl;
}

int main() {
    int pipefd[2];
    int ret = pipe(pipefd);
    if (ret < 0) return 1;
    // cout << pipefd[0] << ' ' << pipefd[1] << endl;

    pid_t id = fork();
    if (id < 0) return 2;
    if (id == 0) {
        close(pipefd[1]);
        Reader(pipefd[0]);
    }
    close(pipefd[0]);
    Writer(pipefd[1]);
    
    int wait_ret = waitpid(id, nullptr, 0);
    if (wait_ret < 0) return 3;
    return 0;
}